﻿using System;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Security.Cryptography;

namespace UploadServer
{
	class Helper
	{
		private static ServerConfigure _ServerConfig;
		public static ServerConfigure ServerConfig
		{
			get
			{
				if (_ServerConfig.IsEmpty)
				{
					var filename = Path.Combine(Environment.CurrentDirectory, "server.xml");
					if (!File.Exists(filename))
					{
						_ServerConfig = ServerConfigure.Default;
						var ser = new XmlSerializer(_ServerConfig.GetType());
						var builder = new StringBuilder();
						using (var writer = XmlWriter.Create(builder))
						{
							ser.Serialize(writer, _ServerConfig);
						}
						File.WriteAllText(filename, builder.ToString(), Encoding.UTF8);
					}
					else {
						var xml = File.ReadAllText(filename, Encoding.UTF8);
						var ser = new XmlSerializer(_ServerConfig.GetType());
						using (var reader = XmlReader.Create(new StringReader(xml)))
						{
							_ServerConfig = (ServerConfigure)ser.Deserialize(reader);
						}
					}
				}
				return _ServerConfig;


			}
		}

		private static Random _Seed = new Random(new Random().Next(int.MinValue, int.MaxValue));

		public static string BitString(byte[] buffer)
		{
			return BitConverter.ToString(buffer).Replace("-", "").ToLower();
		}

		public static string NewId()
		{
			return Guid.NewGuid().ToString("N").ToLower();
		}
		public static string NewSession()
		{
			byte[] buffer = new byte[16];
			_Seed.NextBytes(buffer);
			return BitString(buffer) + NewId();
		}
		public static string Salt()
		{
			byte[] buffer = new byte[8];
			_Seed.NextBytes(buffer);
			return BitString(buffer);
		}
		public static string Sha1(string s)
		{
			s = s ?? String.Empty;
			byte[] buffer = Encoding.UTF8.GetBytes(s);
			using (var sha1 = SHA1.Create())
			{
				buffer = sha1.ComputeHash(buffer);
			}
			return BitString(buffer);
		}
		public static string Md5(string s)
		{
			s = s ?? String.Empty;
			byte[] buffer = Encoding.UTF8.GetBytes(s);
			using (var md5 = MD5.Create())
			{
				buffer = md5.ComputeHash(buffer);
			}
			return BitString(buffer);
		}
	}
}
